package org.gw.building.ctrl;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.gw.building.dto.Tyxx;
import org.gw.building.model.Bm;
import org.gw.building.model.Tyxxb;
import org.gw.building.model.Tyxxrzb;
import org.gw.building.model.base.*;
import org.gw.building.repositories.BmRepository;
import org.gw.building.repositories.TyxxbRepository;
import org.gw.building.repositories.TyxxrzbRepository;
import org.gw.building.util.Constant;
import org.gw.ylc.base.context.RequestContextHolder;
import org.gw.ylc.base.interceptor.RequestPermission;
import org.gw.ylc.base.model.Administrator;
import org.gw.ylc.base.model.Department;
import org.gw.ylc.base.model.Student;
import org.gw.ylc.base.model.UserInfo;
import org.gw.ylc.base.repositories.AdministratorRepository;
import org.gw.ylc.base.repositories.DepartmentRepository;
import org.gw.ylc.base.repositories.StudentRepository;
import org.gw.ylc.base.util.PermissionUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by qwx89 on 2017/7/23.
 */
@RestController
@RequestMapping("tzzgl")
public class BmCtrl {

    @Autowired
    private BmRepository bmRepository;

    @Autowired
    private DepartmentRepository departmentRepository;

    @Autowired
    private TyxxrzbRepository tyxxrzbRepository;

    @Autowired
    private TyxxbRepository tyxxbRepository;

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private AdministratorRepository administratorRepository;

    @RequestMapping(value = "list")
    @RequestPermission(value = {RequestPermission.DEPARTMENT})
    public Page<Bm> queryBm(String mc, String cc, Boolean sfyx) {
        UserInfo userInfo = RequestContextHolder.get().getUser();
        String departmentId = userInfo.getDepartment();
        if (StringUtils.isEmpty(departmentId) && userInfo.getType() != 1) {
            throw new RuntimeException("该用户没有权限");
        }
        List<Bm> bms = bmRepository.findBySsyx(departmentId);
        if (CollectionUtils.isEmpty(bms)) {
            Department department = departmentRepository.findOne(departmentId);
            Cc _cc = new Cc();
            _cc.setDm("2");
            Bm bm = Bm.builder().ssyx(department.getCode()).mc(department.getName()).
                    cc(_cc).xsyx(department.getIsStuDep() == 1).sfyx(true).px(department.getOrder())
                    .build();
            bmRepository.save(bm);
        }
        return bmRepository.queryBm(PermissionUtil.toLikeString(mc), cc, sfyx, departmentId, RequestContextHolder.get().getPageRequest());
    }

    @RequestMapping("lsbm")
    @RequestPermission(value = {RequestPermission.DEPARTMENT})
    public List<Bm> queryLsbm(String cc) {
        UserInfo userInfo = RequestContextHolder.get().getUser();
        String departmentId = userInfo.getDepartment();
        return bmRepository.queryLsbm(cc, departmentId);
    }

    @RequestMapping("addBm")
    @RequestPermission(value = {RequestPermission.DEPARTMENT})
    @Transactional
    public Object addBm(Bm bm) {
        UserInfo userInfo = RequestContextHolder.get().getUser();
        String departmentId = userInfo.getDepartment();
        bm.setSsyx(departmentId);
        Tyxx tyxx = bm.getTyxx();
        bm = bmRepository.save(bm);
        String xh = null;
        if (tyxx != null && StringUtils.isNotBlank((xh = tyxx.getXh()))) {
            Tyxxb tyxxb = tyxxbRepository.findZbsjByBranch(departmentId, bm.getId());
            Student stu = studentRepository.findByXh(xh);
            if (tyxxb == null) {
                addTyxx(stu,bm,departmentId);
                //新增admin
                addAdmin(stu,departmentId);
            } else if (!StringUtils.equals(tyxxb.getXh(), xh)) {
                //备份团员信息
                copyTyxx2Tyxxrz(tyxxb);
                //删除admin
                deleteAdmin(tyxxb.getXh());
                //删除tyxxb
                tyxxbRepository.deleteByXh(tyxxb.getXh());
                //新增团员信息
                addTyxx(stu,bm,departmentId);
                //新增admin
                addAdmin(stu,departmentId);
            }
        }
        return bm;
    }

    @Transactional
    private void addAdmin(Student stu, String departmentId) {
        Administrator administrator = new Administrator();
        administrator.setEmployeeNo(stu.getXh());
        administrator.setApp(Constant.app);
        administrator.setManaDep(departmentId);
        administrator.setName(stu.getName());
        administrator.setStatus(1);
        administrator.setType(4);
        administratorRepository.save(administrator);
    }

    @Transactional
    private void deleteAdmin(String xh) {
        administratorRepository.deleteBranchAdmin(xh, Constant.app);
    }

    @Transactional
    private void addTyxx(Student stu, Bm bm, String departmentId) {
        Tyxxb.TyxxbBuilder builder = Tyxxb.builder();
        builder = builder.yx(departmentId).
                zbmc(bm).xh(stu.getXh()).xm(stu.getName()).mz(new Mz(stu.getEthnicGroup().getCode())).
                xb(stu.getSex() == 0 ? new Xb("1") : new Xb("2")).
                csrq(stu.getBirthdate()).zzmm(new Zzmm(stu.getPolicital().getCode())).
                whcd(stu.getWhcd()).tgb(false).zbsj(true).zbwy(false).tnzw("支部书记").
                lx(new Rylx("1")).sjly(new Sjly("1")).scbz(false);
        Tyxxb tyxxb = builder.build();
        tyxxbRepository.save(tyxxb);
    }

    @Transactional
    private void copyTyxx2Tyxxrz(Tyxxb tyxxb) {
        Tyxxrzb rzb = new Tyxxrzb();
        BeanUtils.copyProperties(tyxxb, rzb);
        rzb.setCzlx(new Czlx("2"));
        Rzsjly sjly = new Rzsjly();
        sjly.setDm("1");
        rzb.setRzsjly(sjly);
        tyxxrzbRepository.save(rzb);
    }

    @RequestMapping("px")
    @RequestPermission(value = {RequestPermission.DEPARTMENT})
    public int getPx() {
        UserInfo userInfo = RequestContextHolder.get().getUser();
        String departmentId = userInfo.getDepartment();
        int maxPx = bmRepository.queryBmMaxPx(departmentId);
        return maxPx + 10;
    }

    @RequestMapping("deleteTzz")
    @RequestPermission(value = {RequestPermission.DEPARTMENT})
    @Transactional
    public Object deleteTzz(String id) {
        UserInfo userInfo = RequestContextHolder.get().getUser();
        String departmentId = userInfo.getDepartment();
        tyxxrzbRepository.deleteByYx(departmentId);
        tyxxbRepository.deleteByYx(departmentId);
        bmRepository.delete(id);
        return id;
    }

    @RequestMapping("tyxx")
    @RequestPermission(value = {RequestPermission.DEPARTMENT})
    public Student queryTyxx(String bmId) {
        UserInfo userInfo = RequestContextHolder.get().getUser();
        String departmentId = userInfo.getDepartment();
        Tyxxb tyxxb = tyxxbRepository.findZbsjByBranch(departmentId, bmId);
        if(tyxxb != null){
            return studentRepository.findByXh(tyxxb.getXh());
        }
        return null;
    }

}
